package com.buyhouse.zhaimao.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * json解析工具类
 */
public class JsonBeans {

	/**
	 * bean list<k,v>
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	public static <T> T getJson(String jsonString, Class<T> cls) {
		T t = null;
		Gson gson = new Gson();
		t = gson.fromJson(jsonString, cls);
		return t;
	}

	/**
	 * list of beans
	 */
	@SuppressWarnings("unchecked")
	public static <T, K> List<T> getJsonList(String jsonString,
			TypeToken<K> type) {
		List<T> list = new ArrayList<T>();
		list.clear();
		Gson gson = new Gson();
		list.addAll((List<T>) gson.fromJson(jsonString, type.getType()));
		return list;// 这样保持了局部变量list的引用 妥还是不妥啊。
	}

	/**
	 * list of String a,b,c
	 * 
	 * @param jsonString
	 * @return
	 */
	public static List<String> getList(String jsonString) {
		List<String> list = new ArrayList<String>();
		Gson gson = new Gson();
		list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
		}.getType());
		return list;

	}

	/**
	 * 复杂Map
	 * 
	 * @param jsonString
	 * @return
	 */
	public static List<Map<String, Object>> getJsonMap(String jsonString) {
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
		Gson gson = new Gson();
		map = gson.fromJson(jsonString,
				new TypeToken<List<Map<String, Object>>>() {
				}.getType());
		return map;
	}

}
